<template>
    <div id="mine">
        <el-card class="box-card" shadow="always">
            <div slot="header" class="clearfix">
                <span class="my">个人信息</span>
            </div>
            <div class="mymain" v-if="userdata">
                <div class="user-info-head clearfix">
                    <el-upload
                        name="head"
                        class="avatar-uploader"
                        action="/api/upload"
                        :style="{'background-image':'url('+ userdata.imgurl +')'}"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </div>
                <div  class="text item">
                    <i class="el-icon-user-solid"></i>用户昵称
                    <div class="pull-right">{{userdata.username}}</div>
                </div>
                <div  class="text item">
                    <i class="el-icon-phone"></i>手机号码
                    <div class="pull-right">{{userdata.phone}}</div>
                </div>
                <div  class="text item">
                    <i class="el-icon-s-promotion"></i>用户邮箱
                    <div class="pull-right">{{userdata.email}}</div>
                </div>
                <div  class="text item">
                    <i class="el-icon-s-custom"></i>所属角色
                    <div class="pull-right">{{userdata.role}}</div>
                </div>
                <div  class="text item">
                    <i class="el-icon-date"></i>创建日期
                    <div class="pull-right">{{userdata.createTime | dateFormat}}</div>
                </div>
            </div>
        </el-card>
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>基本资料</span>
            </div>
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="基本资料" name="first">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="用户昵称" prop="name">
                            <el-input v-model="ruleForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="用户手机号" prop="phone">
                            <el-input v-model="ruleForm.phone"></el-input>
                        </el-form-item>
                        <el-form-item prop="email" label="邮箱">
                            <el-input v-model="ruleForm.email"></el-input>
                        </el-form-item>
                        <el-form-item label="性别" prop="sex">
                            <el-radio-group v-model="ruleForm.sex">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="2">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="mini" @click="submitForm('ruleForm');">保存</el-button>
                            <el-button type="danger" size="mini" @click="closePage()">关闭</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="修改密码" name="second">
                    <el-form :model="ruleForm2" status-icon :rules="rules" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="旧密码" prop="oldpass">
                            <el-input type="password" v-model="ruleForm2.oldpass" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="新密码" prop="pass">
                            <el-input type="password" v-model="ruleForm2.pass" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="checkPass">
                            <el-input type="password" v-model="ruleForm2.checkPass" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="mini" @click="submitForm2('ruleForm2')">保存</el-button>
                            <el-button type="danger" size="mini" @click="closePage()">关闭</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>
<script>
import qs from 'qs';
export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'));
        } else {
          if (this.ruleForm2.checkPass !== '') {
            this.$refs.ruleForm2.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm2.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      var validatePass3 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入原密码'));
        } else if (value !== this.userdata.upwd) {
          callback(new Error('原密码不正确!'));
        } else {
          callback();
        }
      };
      return {
        activeName: 'first',
        password:'',
        userdata:this.$store.state.userinfo,
        uid:this.$store.state.userinfo.uid,
        ruleForm: {
          name:this.$store.state.userinfo.username,
          phone:this.$store.state.userinfo.phone,
          email:this.$store.state.userinfo.email,
          sex:this.$store.state.userinfo.sex=="男" ? 1:2
        },
        ruleForm2: {
          oldpass: '',
          pass:'',
          checkPass:''
        },
        imageUrl: '',
        file:'',
        rules: {
          name: [
            { required: true, message: '请输入用户昵称', trigger: 'blur' },
            { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
          ],
          phone:[
            { required: true, message: '手机号不能为空', trigger: 'blur'},
            { message: '手机号必须为数字值', trigger: ['blur', 'change']}
          ],
          email:[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          oldpass: [
            {required: true, validator: validatePass3, trigger: 'blur' }
          ],
          pass: [
            {required: true, validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            {required: true, validator: validatePass2, trigger: 'blur' }
          ],
        },       
      };
    },
    created(){
      
    },
    methods: {
      handleClick(tab, event) {
        console.log(tab, event);
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        console.log(this.imageUrl);
        this.getimg();
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }, 
      getimg(){
        let obj={
          uid:this.uid
        }
        this.$http.put("http://localhost:5050/api/updataimgurl",qs.stringify(obj)).then((response)=>{
          if(response.data.flag===1){
              this.$message({type: 'success',message: '设置头像成功，原头像已删除!'});
              this.userdata.imgurl=response.data.imgurl;
              this.$store.commit("updata",this.userdata);
              console.log(this.$store.state.userinfo);
            }else{
              this.$message.error('删除失败！');
            }
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.updatainfo();
          } else {
            this.$message.error('修改个人失败');
            return false;
          }
        });
      },
      submitForm2(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.updatapwd();
            this.$refs[formName].resetFields();
          } else {
            this.$message.error('修改密码失败');
            return false;
          }
        });
      },
      closePage(){
        this.$router.push('/home');
      },
      updatapwd(){
        let obj={
          uid:this.uid,
          pwd:this.ruleForm2.pass
        }
        this.$http.put("http://localhost:5050/api/updatapwd",qs.stringify(obj)).then((response)=>{
          if(response.data.flag===1){
              this.password=response.data.pwd;
              console.log(this.password);
              this.userdata.upwd=this.password,
              this.$store.commit("updata",this.userdata);
              this.$message({type: 'success',message: '修改密码成功'});
            }else{
              this.$message.error('修改密码失败！');
            }
        })
      },
      updatainfo(){
        let sex='';
        if(this.ruleForm.sex===1){
          sex="男"
        }else{
          sex="女"
        }
        let obj={
          uid:this.uid,
          name:this.ruleForm.name,
          phone:this.ruleForm.phone,
          email:this.ruleForm.email,
          sex:sex
        }
        console.log(obj);
        this.$http.put("http://localhost:5050/api/updatainfo",qs.stringify(obj)).then((response)=>{
          if(response.data.flag===1){
              this.userdata.username=this.ruleForm.name,
              this.userdata.phone=this.ruleForm.phone,
              this.userdata.email=this.ruleForm.email,
              this.userdata.sex=this.ruleForm.sex,
              this.$store.commit("updata",this.userdata);
              this.$message({type: 'success',message: '修改个人信息成功'});
            }else{
              this.$message.error('修改个人信息失败！');
            }
        })
      }
    },
};
</script>
<style scoped>
#mine{
    padding: 20px;
}
.text {
    font-size: 13px;
    text-align: left;
  }

  .item {
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #ebeef5;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 26%;
    min-width: 325px;
    box-sizing: border-box;
    float: left;
  }
  .box-card:nth-child(2){
      margin-left: 20px;
      width: 72%;
      min-width: 900px;
  }
  .box-card .my{
      color:#303133;
      font-size: 16px;
  }
  .box-card .mymain .user-info-head{
      text-align: center;
      border-bottom: 1px solid #ebeef5;
      padding-bottom: 20px;
      position: relative;
  }
  .pull-right {
      float: right!important;
      font-size: 13px;
  }
  .avatar-uploader{
    width: 120PX;
    height: 120px;
    border-radius: 50%;
    cursor: pointer;
    overflow: hidden;
    background-size: 100% 100%;
    border: 1px solid #e6ebf5;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
  }
  .avatar-uploader-icon{
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
    display: none;
  }
  .avatar-uploader:hover .avatar-uploader-icon{
    display: block;
    background-color: rgba(0, 0, 0, .3);
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
  
</style>